<template>
	<div :id="props.id"
		 :style="{width: props.width, height: props.height}"
	></div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import {onMounted, onUnmounted, defineProps} from 'vue';

export interface BarInterface {
	title: string;
	xData: string[];
	yData: number[];
}

const props = defineProps({
	id: {
		type: String,
		default: 'line'
	},
	theme: {
		type: String,
		default: '' // dark
	},
	width: {
		type: String,
		default: '100%'
	},
	height: {
		type: String,
		default: '100%'
	},
	data: {
		type: Object,
		default: () => {
			return {
				title: '',
				xData: [],
				yData: []
			}
		}
	},
	option: {
		type: Object,
		default: () => {
			return {
				grid: {
					left: '3%',
					right: '4%',
					bottom: '3%',
					containLabel: true
				},
				tooltip: {
					trigger: 'axis'
				},
				legend: {
					type: 'plain',
					show: true,
					data: [],
					center: 'auto'
				},
				title: {
					text: '',
				},
				xAxis: {
					type: 'category',
					data: []
				},
				yAxis: {
					type: 'value'
				},
				series: [
					{
						data: [],
						type: 'bar'
					}
				]
			}
		}
	}
});

onMounted(() => {
	init()
});

function init() {
	const basicBar = echarts.init(document.getElementById(props.id), props.theme);
	props.option.title.text = props.data.title;
	props.option.xAxis.data = props.data.xData;
	props.option.series[0].data = props.data.yData;

	basicBar.setOption(props.option);
}

function resize() {
	const basicBar = echarts.init(document.getElementById(props.id), props.theme);
	basicBar.resize();
}

onMounted(() => {
	window.addEventListener('resize', resize);
});

onUnmounted(() => {
	window.removeEventListener('resize', resize);
});

function refreshChart(data: BarInterface) {
	const basicBar = echarts.init(document.getElementById(props.id), props.theme);
	props.option.title.text = data.title;
	props.option.xAxis.data = data.xData;
	props.option.legend.data = data?.legendData || []
	props.option.series = data.yData;
	basicBar.setOption(props.option);
}

defineExpose({
	refreshChart
});


</script>

<style scoped>

</style>
